package com.cgycms.prototype.config;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.cgycms.prototype.UserProjectManagerService;
import com.cgycms.prototype.constant.ViewAuthConstant;
import com.cgycms.prototype.model.UserProjectModel;
import com.cgycms.prototype.util.ProjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: 超哥呦
 * @Description: 拦截器配置 拦截直接访问项目静态资源控制访问密码
 * @date: 2021/11/13 23:31
 **/
@Component
public class WebPrototypeInterceptor implements HandlerInterceptor {


    @Autowired
    private UserProjectManagerService userProjectManagerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getContextPath() + "/view/viewLogin?uri=" + request.getRequestURI();
        String code = ProjectUtil.getProjectCode(request.getRequestURI());
        Cookie cookie = ServletUtil.getCookie(request, ViewAuthConstant.ACCESS_PASSWORD_KEY + code);
        UserProjectModel userProjectEntity = userProjectManagerService.getProjectDataByUri(request.getRequestURI());
        //没有找到项目，404
        if (ObjectUtil.isNull(userProjectEntity)) {
            response.sendRedirect(request.getContextPath() + "/404");
            return false;
        }
        //没有访问密码
        if (userProjectEntity.getPassType() == 0) {
            return true;
        }
        //没有找到cookie
        if (StringUtils.isEmpty(cookie)) {
            response.sendRedirect(uri);
            return false;
        }
        //密码不正确
        if (!userProjectEntity.getProjectPassword().toLowerCase().equals(cookie.getValue().toLowerCase())) {
            response.sendRedirect(uri);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}
